package com.lyc.controller;

import com.lyc.constant.Constant;
import com.lyc.entity.Address;
import com.lyc.entity.User;
import com.lyc.entity.vo.AddressVo;
import com.lyc.service.IAddressService;
import org.apache.commons.math3.analysis.function.Add;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.ResponseBody;

import javax.servlet.http.HttpSession;
import java.util.List;

@Controller
@RequestMapping("/address")
public class AddressController {

    @Autowired
    private IAddressService addressService;

    @RequestMapping("/myAddress")
    public String myAddress(HttpSession session, Model model) {
        User user = (User) session.getAttribute(Constant.CURRENT_USER);
        if (user != null) {
            List<AddressVo> addressList = addressService.getMyAddress(user.getUid());
            model.addAttribute("addressList", addressList);
        }
        return "/user/address_management";
    }

    @RequestMapping("/handleAddress")
    public String handleAddress(HttpSession session, Address address) {
        User user = (User) session.getAttribute(Constant.CURRENT_USER);
        if (user != null)
            address.setUid(user.getUid());
        addressService.addOrUpdate(address);
        return "redirect:/address/myAddress";
    }

    @RequestMapping("/setDefaultAddress")
    @ResponseBody
    public String setDefaultAddress(HttpSession session,int aid){
        User user = (User) session.getAttribute(Constant.CURRENT_USER);
        addressService.setDefaultAddress(user==null?null:user.getUid(),aid);
        return Constant.OPERATE_SUCCESS;
    }

    @RequestMapping("/deleteAddress")
    public String deleteAddress(int aid){
        addressService.deleteAddress(aid);
        return "redirect:/address/myAddress";
    }

    @RequestMapping("/getAddressById")
    @ResponseBody
    public Address getAddressById(int aid){
        return addressService.getAddressByAid(aid);
    }

    @RequestMapping("/handleAddressAjax")
    @ResponseBody
    public String handleAddressAjax(HttpSession session, Address address) {
        User user = (User) session.getAttribute(Constant.CURRENT_USER);
        if (user != null)
            address.setUid(user.getUid());
        addressService.addOrUpdate(address);
        return Constant.OPERATE_SUCCESS;
    }

    @RequestMapping("/delAddressAjax")
    @ResponseBody
    public String delAddressAjax(int aid){
        addressService.deleteAddress(aid);
        return Constant.OPERATE_SUCCESS;
    }
}
